import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

/**
 * @author lys
 * 借还图书
 */
public class BorrowAndReturn {
    private static BorrowAndReturn instance;

    public static BorrowAndReturn getInstance() {
        if(instance == null) instance = new BorrowAndReturn();
        return instance;
    }

    public JLayeredPane jLayeredPane = new JLayeredPane();
    // 标签
    private JLabel jLabel = new JLabel("图书借还");
    private JLabel jLabel2 = new JLabel("请输入书号：");
    private JLabel jLabel3 = new JLabel("书名：");
    private JLabel jLabel4 = new JLabel();
    private JLabel jLabel5 = new JLabel("作者：");
    private JLabel jLabel6 = new JLabel();
    private JLabel jLabel7 = new JLabel("状态：");
    private JLabel jLabel8 = new JLabel();
    private JLabel jLabel9 = new JLabel("书号：");
    private JLabel jLabel10 = new JLabel();

    // 文本框
    private JTextField field = new JTextField(20);
    // 大小
    // private Dimension dimension = new Dimension(220, 20);
    // 按钮
    private JButton button = new JButton("检索");
    private JButton button2 = new JButton("归还");
    private JButton button3 = new JButton("借阅");

    // 面板
    private JPanel jPanel = new JPanel();
    // 字体
    private Font font = new Font("宋体", Font.BOLD, 60);
    private Font font2 = new Font("宋体", Font.BOLD, 30);
    private Font font3 = new Font("宋体", Font.BOLD, 26);

    // 接收此账号的用户名
    private String user;

    // 接收图书查询表格，实现实时更新
    private DefaultTableModel model = new DefaultTableModel();
    int id;

    private BorrowAndReturn() {
        // 改变背景图片
        Icon i = new ImageIcon(BorrowAndReturn.class.getResource("img/7.jpg"));
        JLabel Label = new JLabel(i);
        Label.setBounds(0, 0, 1200, 800);

        // 标签
        jLabel.setFont(font);
        jLabel.setBounds(480, 35, 800, 100);
        jLabel.setForeground(Color.white);

        jLabel2.setFont(font2);
        jLabel2.setBounds(280, 164, 250, 30);
        jLabel2.setForeground(Color.white);

        // 文本框
        field.setFont(font2);
        field.setBackground(Color.white);
        field.setBounds(480, 164, 250, 30);
        field.setForeground(Color.white);
        field.setOpaque(false);

        // 按钮
        button.setFont(font2);
        button.setBounds(780, 160, 100, 40);
        button.setForeground(Color.white);
        button.setBackground(Color.white);
        button.setOpaque(false);

        // 面板
        jPanel.setBounds(270, 220, 620, 450);
        jPanel.setBackground(Color.white);
        jPanel.setLayout(null);

        // 面板上标签及按钮
        jLabel3.setFont(font2);
        jLabel4.setFont(font2);
        jLabel5.setFont(font2);
        jLabel6.setFont(font2);
        jLabel7.setFont(font2);
        jLabel8.setFont(font2);
        jLabel9.setFont(font2);
        jLabel10.setFont(font2);

        button2.setFont(font3);
        button3.setFont(font3);

        jLabel3.setForeground(Color.black);
        jLabel4.setForeground(Color.black);
        jLabel5.setForeground(Color.black);
        jLabel6.setForeground(Color.black);
        jLabel7.setForeground(Color.black);
        jLabel8.setForeground(Color.black);
        jLabel9.setForeground(Color.black);
        jLabel10.setForeground(Color.black);

        button2.setForeground(Color.black);
        button3.setForeground(Color.black);

        jLabel9.setBounds(100, 20, 100, 50);
        jLabel10.setBounds(200, 20, 400, 50);
        jLabel3.setBounds(100, 90, 100, 50);
        jLabel4.setBounds(200, 90, 400, 50);
        jLabel5.setBounds(100, 160, 100, 50);
        jLabel6.setBounds(200, 160, 400, 50);
        jLabel7.setBounds(100, 230, 100, 50);
        jLabel8.setBounds(200, 230, 400, 50);

        button2.setBounds(80, 310, 90, 50);
        button3.setBounds(460, 310, 90, 50);
        button2.setBackground(Color.white);
        button2.setOpaque(false);
        button3.setBackground(Color.white);
        button3.setOpaque(false);

        jPanel.add(jLabel3);
        jPanel.add(jLabel4);
        jPanel.add(jLabel5);
        jPanel.add(jLabel6);
        jPanel.add(jLabel7);
        jPanel.add(jLabel8);
        jPanel.add(jLabel9);
        jPanel.add(jLabel10);
        jPanel.add(button2);
        jPanel.add(button3);
        jPanel.setVisible(false);

        jPanel.setOpaque(false);

        // 加入分层窗口
        jLayeredPane.add(Label, new Integer(0), 0);
        jLayeredPane.add(jLabel, new Integer(100), 1);
        jLayeredPane.add(jLabel2, new Integer(100), 2);
        jLayeredPane.add(field, new Integer(100), 3);
        jLayeredPane.add(button, new Integer(100), 4);
        jLayeredPane.add(jPanel, new Integer(100), 5);


        button.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        jPanel.setVisible(true);
                        String bookId = field.getText();
                        Book book = returnSearch(bookId);
                        if(book != null){
                            jLabel10.setText(String.valueOf(book.getBookId()));
                            jLabel4.setText(book.getBookName());
                            jLabel6.setText(book.getWriter());
                            if(book.isBorrowed()){
                                jLabel8.setText("已借");
                            }else{
                                jLabel8.setText("在馆");
                            }
                        }
                    }
                }
        );

        button2.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String bookId = field.getText();
                        returnBook(bookId);
                    }
                }
        );

        button3.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String bookId = field.getText();
                        borrowBook(bookId);
                    }
                }
        );

        button.setFocusPainted(false);
        button2.setFocusPainted(false);
        button3.setFocusPainted(false);
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setModel(DefaultTableModel model) {
        this.model = model;
    }


    public void empty() {
        jLabel4.setText("");
        jLabel6.setText("");
        jLabel8.setText("");
        jLabel10.setText("");
    }

    /**
     * @author zj
     * @param bookId
     * @return 根据书号搜索结果
     */
    public static Book returnSearch(String bookId){
        ArrayList<Book> books = Search.getInstance().returnSearch(5, bookId);
        if(books != null)
            return books.get(0);
        return null;
    }

    /**
     *
     * @param type
     * @param bookId
     * @return 由int标志的事件
     */
    public int checkBook(int type, String bookId){
        String loginUser = Login.loginUser;
        ResultSet rs = null;
        String sql = "select * from borrowinfo where bookid = ? and borrowuser = ?";
        Connection con = DatabaseConnection.getInstance().getCon();
        try{
            PreparedStatement preSql = con.prepareStatement(sql);
            preSql.setString(1, bookId);
            preSql.setString(2, loginUser);
            rs = preSql.executeQuery();
            if(type == 1) {
                if (!rs.next()) {
                    return 1;
                }
                Boolean isReturned = rs.getBoolean("isreturned");
                if (isReturned) {
                    return 2;
                } else {
                    return 3;
                }
            }
            else {
                sql = "select * from borrowinfo where bookid = ? and borrowuser = ? and isreturned = 1";
                preSql = con.prepareStatement(sql);
                preSql.setString(1,bookId);
                preSql.setString(2, loginUser);
                rs = preSql.executeQuery();
                if(rs.next()){
                    return 2;
                }
//                if(rs.next()) {
//                    Boolean isReturned = rs.getBoolean("isreturned");
//                    if (isReturned) {
//                        return 2;
//                    }
//                }
                sql = "select * from book where bookid = ?";
                preSql = con.prepareStatement(sql);
                preSql.setString(1, bookId);
                rs = preSql.executeQuery();
                if(rs.next()){
                    Boolean isBorrowed = rs.getBoolean("isborrowed");
                    if(isBorrowed){
                        return 4;
                    }
                    else{
                        return 5;
                    }
                }
            }
        }
        catch(Exception e){
            System.out.println(e);
        }
        return 6;
    }

    /**
     * 还书
     * @param bookId
     */
    public void returnBook(String bookId){
        Book book = returnSearch(bookId);
        int flag = checkBook(1, bookId);
        if(flag == 1 && book != null){
            JOptionPane.showMessageDialog(null, "您没有借过该书！");
            return;
        }
        else if(flag == 2){
            JOptionPane.showMessageDialog(null, "您已归还该书！");
            return;
        }
        else if(flag == 3){
            String loginUser = Login.loginUser;
            String sql = "update borrowinfo set isreturned = 1, returntime = ? where bookid = ? and borrowuser = ?";
            Connection con = DatabaseConnection.getInstance().getCon();
            try{
                PreparedStatement preSql = con.prepareStatement(sql);
                preSql.setString(1, Time.getTime());
                preSql.setString(2, bookId);
                preSql.setString(3, loginUser);
                int ok = preSql.executeUpdate();

                sql = "update book set isborrowed = 0 where bookid = ?";
                preSql = con.prepareStatement(sql);
                preSql.setString(1, bookId);
                ok = preSql.executeUpdate();

                JOptionPane.showMessageDialog(null, "还书成功");
                jLabel8.setText("在馆");
                return;
            }catch(Exception e){
                System.out.println(e);
            }

        }
    }

    /**
     * 借书
     * @param bookId
     */
    public void borrowBook(String bookId){
        Book book = returnSearch(bookId);
        int flag = checkBook(2, bookId);
        if(flag == 2){
            JOptionPane.showMessageDialog(null, "您已借阅过该书！为保证绝大多数用户需求，同一本书一个用户仅能借阅一次。图书馆体量小，还请用户见谅!");
            return;
        }
        else if(flag == 4){
            JOptionPane.showMessageDialog(null, "该书已经被人借走了");
            return;
        }
        else if (flag == 5){
            String loginUser = Login.loginUser;
            book = returnSearch(bookId);
            String sql = "insert into borrowinfo values (?,?,?,?, 0, null)";
            Connection con = DatabaseConnection.getInstance().getCon();
            try{
                PreparedStatement preSql = con.prepareStatement(sql);
                preSql.setString(1, bookId);
                preSql.setString(2, book.getBookName());
                preSql.setString(3, loginUser);
                preSql.setString(4, Time.getTime());
                int ok = preSql.executeUpdate();

                sql ="update book set isborrowed = 1 where bookid = ?";
                preSql = con.prepareStatement(sql);
                preSql.setString(1, bookId);
                ok = preSql.executeUpdate();
                JOptionPane.showMessageDialog(null, "借书成功");
                jLabel8.setText("已借");
                return;
            }catch(Exception e){
                System.out.println(e);
            }
        }
    }
    public static void removeInstance(){
        instance = null;
    }
}
